﻿using System;
using System.Runtime.Serialization;
using System.Security;

namespace Pfz.RemoteGaming.Internal
{
	[Serializable]
	internal sealed class _RemoteGameComponentReference:
		IObjectReference
	{
		private long _ownerId;
		private long _id;
		public _RemoteGameComponentReference(SerializationInfo info, StreamingContext context)
		{
			_ownerId = info.GetInt64("_ownerId");
			_id = info.GetInt64("_id");
		}
		
		[SecurityCritical]
		public object GetRealObject(StreamingContext streamingContext)
		{
			var context = streamingContext.Context as _RemoteGameContext;
			if (context == null)
				throw new RemoteGameException("You can't deserialize game components outside of a game.");

			if (_ownerId != context._ownerId)
				throw new RemoteGameException("Error deserializing game component.");

			RemoteGameComponent result;
			lock(context._lock)
				if (!context._components.TryGetValue(_id, out result))
					throw new RemoteGameException("Can't find game component.");

			return result;
		}
	}
}
